import { defineComponent, ref, nextTick, watch, PropType, toRefs, onBeforeUnmount } from 'vue'
import Particle, { SHAPES } from '@/lib/js/utils/particle'
import { delayExecution } from '@/lib/js/utils/tool'

export default defineComponent({
  emits: ['animationend'],
  props: {
    redraw: Boolean,
    backgroundColor: String,
    colors: {
      type: Array as PropType<Array<string>>
    },
    types: {
      type: [Array, Number] as PropType<Array<SHAPES> | SHAPES>
    },
    sideNumber: {
      type: [Array, Number] as PropType<Array<number> | number>
    }
  },
  setup(props, context) {
    const { redraw } = toRefs(props)
    const { emit } = context
    const canvas = ref<HTMLCanvasElement>()
    const particle = ref<Particle | null>(null)
    const isAnimationExecing = ref<boolean>(false)
    /**
     * @description 绘制粒子动画函数
     */
    const draw = async() => {
      const { backgroundColor, colors, types, sideNumber } = props
      isAnimationExecing.value = true;
      if (particle.value) {
        particle.value.draw()
      } else {
        nextTick(() => {
          const mycanvas = canvas.value as HTMLCanvasElement
          particle.value = new Particle(mycanvas, {
            backgroundColor,
            colors,
            types,
            sideNumber,
            animationEnd: () => {
              isAnimationExecing.value = false;
              emit('animationend')
            }
          })
        })
      }
    }
    /**
     * @description 销毁粒子动画
     */
    const destory = () => {
      particle.value && particle.value.destory()
      isAnimationExecing.value = false
    }
    draw()
    watch([redraw], async([isShow]) => {
      if((isAnimationExecing.value && isShow) || !isShow) {
        destory();
        await delayExecution(50)
      }
      if (!isShow) return;
      draw()
    })
    onBeforeUnmount(() => {
      return destory()
    })
    return () => <canvas ref={canvas} style="width: 100%; height: 100%" />
  }
})
